<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="设备类型" prop="equipmentType">
        <el-select
          v-model="queryParams.equipmentType"
          placeholder="请选择设备类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in equipmentTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
        >
          搜索
        </el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:properties:add']"
        >
          新增
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="propertiesList" @row-click="toClick">
      <el-table-column label="#" align="center" prop="id" width="55" />
      <el-table-column label="设备类型" align="center" prop="val" />
      <el-table-column label="自定义属性" align="center" prop="count" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['system:properties:edit']"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备属性对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="getDialogWidth()" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentType">
              <el-select
                v-model="form.equipmentType"
                placeholder="请选择设备类型"
                :disabled="title == '修改设备属性'"
              >
                <el-option
                  v-for="dict in equipmentTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button class="ml10" type="primary" @click="addtoList()">
              追加属性
            </el-button>
          </el-col>
        </el-row>

        <el-row v-for="(item, index) in addList" :key="index">
          <el-col :span="10">
            <el-form-item :label="'属性' + (index + 1)">
              <el-input
                v-model="item.deviceName"
                placeholder="请输入属性名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="pl10">
            <el-select
              v-model="item.deviceCondition"
              placeholder="请选择数据类型"
              @change="selectSec(item)"
              @visible-change="selectSec(item)"
            >
              <el-option
                v-for="dict in propertyOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-col>
          <el-col :span="6" class="pl10">
            <div>
              <el-select
                v-show="item.showSelect"
                v-model="item.unit"
                placeholder="请选择属性单位"
              >
                <el-option
                  v-for="dict in unitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
              <el-select
                v-show="item.showDic"
                v-model="item.dataSource"
                placeholder="请选择所属字典名称"
              >
                <el-option
                  v-for="dict in selectOptions"
                  :key="dict.dictType"
                  :label="dict.dictName"
                  :value="dict.dictType"
                />
              </el-select>
            </div>
          </el-col>
          <el-col :span="1">
            <i
              @click="doDelete(index)"
              class="el-icon-remove"
              style="color: red; font-size: 35px; padding-left: 10px;"
            ></i>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="danger"
          plain
          @click="handleDelete(form)"
          v-if="title == '修改设备属性'"
          v-hasPermi="['system:properties:remove']"
        >
          删 除
        </el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" style="width: 120px;">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProperties,
  getProperties,
  delProperties,
  addProperties,
  updateProperties,
  exportProperties,
  getDicSelect,
} from '@/api/deviceproperties/properties'

export default {
  name: 'Properties',
  components: {},
  data() {
    return {
      propertiesList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //设备类型下拉选
      equipmentTypeOptions: [],
      propertyOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderby: null,
        equipmentType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      addList: [],
      unitOptions: [],
      delIds: [],
      selectOptions: [],
    }
  },
  activated() {
    this.getList()
    this.getDicts('equipment_type').then((response) => {
      this.equipmentTypeOptions = response.data
    })
    this.getDicts('property_condition').then((response) => {
      this.propertyOptions = response.data
    })
    this.getDicts('num_unit').then((response) => {
      this.unitOptions = response.data
    })
    getDicSelect().then((response) => {
      this.selectOptions = response.rows
    })
  },
  created() {
    this.getList()

    this.getDicts('equipment_type').then((response) => {
      this.equipmentTypeOptions = response.data
    })
    this.getDicts('property_condition').then((response) => {
      this.propertyOptions = response.data
    })
    this.getDicts('num_unit').then((response) => {
      this.unitOptions = response.data
    })
    getDicSelect().then((response) => {
      this.selectOptions = response.rows
    })
  },
  methods: { 
    toClick(row){
      this.handleUpdate(row)
    },
    doDelete(i) {
      if (this.addList[i].id) {
        this.delIds.push(this.addList[i].id)
        this.addList.splice(i, 1)
      } else {
        this.addList.splice(i, 1)
      }
    },
    selectSec(e) {
      console.log(e)
      switch (true) {
        case e.deviceCondition == 'number' || e.deviceCondition == 'double' || e.deviceCondition == '100' ||
          e.deviceCondition == '200':
          this.$set(e, 'showSelect', true)
          this.$set(e, 'showDic', false)
          this.$set(e, 'dataSource', '')
          break
        case e.deviceCondition == 'select' ||
          e.deviceCondition == 'radio' ||
          e.deviceCondition == 'checkbox':
          this.$set(e, 'showDic', true)
          this.$set(e, 'showSelect', false)
          this.$set(e, 'unit', '')
          break
        case
          e.deviceCondition == 'textarea':
          this.$set(e, 'unit', '')
          this.$set(e, 'dataSource', '')
          this.$set(e, 'showSelect', false)
          this.$set(e, 'showDic', false)
          break
        default:
          break
      }
    },
    addtoList() {
      this.addList.push({})
    },
    /** 查询设备属性列表 */
    getList() {
      listProperties(this.queryParams).then((response) => {
        this.propertiesList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentType: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.addList = []
      this.open = true
      this.title = '添加设备属性'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.key
      getProperties(id).then((response) => {
        let formMap = {
          equipmentType: response.rows[0].key,
        }

        this.$nextTick(() => {
          this.open = true
          this.form = formMap
          this.addList = response.rows[0].data
          this.addList.forEach((e) => {
            if (
              e.deviceCondition == 'number' ||
              e.deviceCondition == 'double' || e.deviceCondition == '100' ||
              e.deviceCondition == '200'
            ) {
              e.showSelect = true
            }
            if (
              e.deviceCondition == 'select' ||
              e.deviceCondition == 'radio' ||
              e.deviceCondition == 'checkbox'
            ) {
              e.showDic = true
            }
          })
        })

        this.title = '修改设备属性'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let data = []
          this.addList.forEach((e) => {
            let map = {
              equipmentType: this.form.equipmentType,
              deviceName: e.deviceName,
              deviceCondition: e.deviceCondition,
            }
            if (e.unit) map.unit = e.unit
            if (e.dataSource) map.dataSource = e.dataSource
            if (e.id) map.id = e.id
            data.push(map)
          })

          addProperties({
            sDevicePropertiesList: data,
            ids: this.delIds.join(),
          }).then((response) => {
            if (this.title == '修改设备属性') {
              this.msgSuccess('修改成功')
              this.delIds = []
            } else {
              this.msgSuccess('新增成功')
              this.delIds = []
            }
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.equipmentType
      this.$confirm('是否删除该设备属性?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delProperties(ids)
        })
        .then(() => {
          this.getList()
          this.open = false
          this.msgSuccess('删除成功')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有设备属性数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportProperties(queryParams)
        })
        .then((response) => {
          this.download(response.msg)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.el-col {
  border: 1px solid transparent;
}
</style>
